import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

// 编写store

const foodStore = createSlice({
  name: "foodsList",
  // 初始化状态
  initialState: {
    foodsList: [], // 商品列表
    menuInd: 0, // 实现菜单栏高亮的索引
    cartList: [], // 购物车列表
  },
  reducers: {
    // 同步修改方法
    // 食物数据列表
    setFoods(state, action) {
      state.foodsList = action.payload;
    },
    // 侧边栏高亮
    changeMenu(state, action) {
      state.menuInd = action.payload;
    },
    // 首次添加到购物车
    setCart(state,action){
      // 如何判断是否添加过  是关键
      // 用 action.payload.id去匹配现有的cartList
      const item = state.cartList.find(item => item.id === action.payload.id)
      item ? item.count ++ : state.cartList.push(action.payload)
    },
    // 购物车递增
    addCart(state,action){
      const item = state.cartList.find(item => item.id === action.payload)
      item.count++
    },
    // 购物车递减
    subCart(state ,action){
      console.log(action.payload,'递减');
      const item = state.cartList.find(item => item.id === action.payload)
      item.count--
      if(item.count === 0) return 
    },
    // 清空购物车
    clearCart(state,action){
      state.cartList = []
    }
  },
});

// 异步修改的方法
const { setFoods  , changeMenu , setCart, addCart ,subCart , clearCart } = foodStore.actions; // 获取actionCreater
// 封装异步函数
const asyncGetFoods = () => {
  // 固定形参dispatch
  return async (dispatch) => {
    const res = await axios.get("http://localhost:3004/takeaway");
    dispatch(setFoods(res.data));
  };
};

export { asyncGetFoods, changeMenu , setCart, addCart ,subCart , clearCart};



export default foodStore.reducer;
